<template>
  <div class="chatDog">
    <div class="chatdogNav">
      <div class="chatdogNav_content">
        <div class="chatdogNav_content_btn" @click="initNewChat"><span>+</span>New chat</div>
        <div class="chatdogNav_content_txt">
          <div class="content_txt_list" v-for="(item, index) in chats" :key="index" :class="{active: index==chatIndex}"
               @click="toggleListItemActive(item, index)">
            <div class="txt_list_title">
              <a><img src="@a/img/sv48.svg"/>{{ item.name }}</a>
              <el-input v-if="item.inputShow" v-model="item.name" placeholder="请输入内容"></el-input>
            </div>
            <div class="txt_list_btn" v-if="index==chatIndex">
              <span><img src="@a/img/sv49.svg" @click="editChat(item, index)"/></span>
              <span><img src="@a/img/sv50.svg" @click="deleteChat(item.id)"/></span>
              <div class="list_btn_clickconfirm" v-if="item.inputShow" @click="editSave(item, index)"><i
                  class="el-icon-check"></i></div>
              <div class="list_btn_clickclose" v-if="item.inputShow" @click="clearName(item, index)"><i
                  class="el-icon-close"></i></div>
            </div>
          </div>
        </div>
        <div class="chatdogNav_content_vip" :class="{ 'is-active': $store.getters.memberInfo.chat_end_time == 0 }">
          <div class="content_vip_left" v-if="$store.getters.memberInfo.chat_end_time > 0">
            <img src="@a/img/vip.svg"/>到期时间：{{ timestampToDate($store.getters.memberInfo.chat_end_time) }}
            <router-link to="/integral/rechargeChatDetails">明细</router-link>
          </div>
          <div class="content_vip_right" @click="rechargeShow = !rechargeShow">
            {{ $store.getters.memberInfo.chat_end_time == 0 ? '立即充值VIP' : '续费' }}
          </div>
        </div>
      </div>

    </div>
    <div class="chatDogHome">
      <template v-if="chatIndex > -1">
        <div class="chat">
          <div v-for="(item, index) in chatList">
            <div class="chat_list user">
              <div class="chat_list_left">
                <div class="list_left_txt">
                  <div class="left_txt_question">
                    <div class="txt_question_p">{{item.content}}</div>
                  </div>
                </div>
              </div>
              <div class="chat_list_right"><img :src="img_dog"/></div>
            </div>
            <div class="chat_list dog">
              <div class="chat_list_left">
                <div class="list_left_txt">
                  <div class="left_txt_question">
                    <markdown-it-vue-light class="txt_question_p" :content="item.response"/>
                  </div>
                </div>
              </div>
              <div class="chat_list_right"><img :src="img_ai"/></div>
            </div>
          </div>
        </div>
        <div class="chatDogHome_submit">
          <div class="chatDogHome_submit_input">
            <div class="submit_input_left">
              <el-input
                  type="textarea"
                  :autosize="{ minRows: 5, maxRows: 5}"
                  :placeholder="prompt_placeholder"
                  v-model="msg"
                  v-enter-prevent="addNewMsg">
              </el-input>
            </div>
            <div class="submit_input_btn">
              <div class="input_btn_click" @click="addNewMsg" v-if="!showLoading"><img src="@a/img/bn29.png"/></div>
              <div class="la-ball-fall la-2x input_btn_loading" :class="{ 'is-active': showLoading }">
                <div></div>
                <div></div>
                <div></div>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-else>
        <div class="chatDogHome_Search">
          <el-input placeholder="搜索提示词" v-model="prompt_keywords" class="input-with-select" v-enter-prevent="addSearch">
            <el-button slot="append" @click="search" icon="el-icon-search"></el-button>
          </el-input>
        </div>
        <div class="chatDogHome_Keywords">
          <div class="chatDogHome_Keywords_list" :class="{active: catIndex === cats.length - 1}"
               @click="changeCat(cats.length - 1)">所有({{cats[cats.length - 1].count}})<img src="@a/img/all.svg"/></div>
          <div class="chatDogHome_Keywords_list" :class="{active: catIndex === cats.length - 2}"
               @click="changeCat(cats.length - 2)">常用({{cats[cats.length - 2].count}})<img src="@a/img/sv51.svg"/></div>
          <div class="chatDogHome_Keywords_list" :class="{active: catIndex === index}" v-if="index < cats.length - 2"
               @click="changeCat(index)" v-for="(item, index) in cats">{{ item.name }}({{item.count}})<span
              :style="{'background': item.colour}"></span></div>
        </div>
        <div class="chatDogHome_content">
          <div @click="usePrompt(item)" class="chatDogHome_content_list" v-for="(item, index) in cats[catIndex].lists"
               :key="index">
            <div class="content_list_top">
              <div class="list_top_dd" v-html="item.name"></div>
              <!-- <div class="list_top_right">
                <div class="list_top_dt" v-if="fav_ids.includes(item.id)" @click="unlike(item.id)"><img src="@a/img/sv51.svg"/><span>移除</span></div>
                <div class="list_top_dt" v-else @click="like(item.id)"><img src="@a/img/sv51.svg"/><span>收藏</span></div>
                <div class="list_top_dt" @click="usePrompt(item)"><span>使用</span></div>
              </div> -->
            </div>
            <div class="content_list_bottom" v-html="item.chat_prompt_front"></div>
          </div>

          <div style=" display: flex; justify-content: center; align-items: center; width: 100%; padding: 20px 0px;">
            <div @click="getMore" style="font-size: 16px; color: #666; cursor: pointer;" v-if="cats[catIndex].lists.length < cats[catIndex].count">加载更多<i class="el-icon-arrow-down" style="margin-left: 5px;"></i></div>
          </div>
        </div>
        <div class="chatDogHome_submit">
          <div class="chatDogHome_submit_tag">
            <div class="submit_tag_list" v-for="(info, index) in infos" :key="index">
              <div v-html="info.name"></div>
              <span @click="handleDelete(index)"><img src="@a/img/sv52.svg"/></span>
            </div>
          </div>
          <div class="chatDogHome_submit_input">
            <div class="submit_input_left">
              <el-input
                  type="textarea"
                  :autosize="{ minRows: 5, maxRows: 5}"
                  :placeholder="prompt_placeholder"
                  v-model="msg"
                  v-enter-prevent="addNewChat">
              </el-input>
            </div>
            <div class="submit_input_btn">
              <div class="input_btn_click" @click="addNewChat" v-if="!showLoading"><img src="@a/img/bn29.png"/></div>
              <div class="la-ball-fall la-2x input_btn_loading" :class="{ 'is-active': showLoading }">
                <div></div>
                <div></div>
                <div></div>
              </div>
            </div>
          </div>
        </div>
      </template>


    </div>

    <member-popup v-if="rechargeShow" @close="rechargeShow = false"></member-popup>


  </div>
</template>


<script>
import {MessageBox, Message} from 'element-ui';
import memberPopup from "@c/common/memberPopup/memberPopup";
import { Loading } from 'element-ui';

import MarkdownItVueLight from 'markdown-it-vue/dist/markdown-it-vue-light.umd.min.js'
import 'markdown-it-vue/dist/markdown-it-vue-light.css'

function removeTags(text) {
  return text.replace(/<[^>]+>/g, '');
}

export default {
  name: "chatDog",
  data() {
    return {
      page: 1,
      prompt_placeholder: '请输入您的问题。(Shift + Enter = 换行)',
      markdownRefresh: false,
      need_code_match: '',
      chatIndex: -1,
      catIndex: -2,
      fav_ids: [],
      prompt_keywords: '',
      cats: [],
      msg: '',
      chats: [],
      infos: [],
      rechargeShow: false,
      showLoading: false,
      img_ai: require("@a/img/bg30.jpg"),
      img_dog: this.baseURL + this.$store.getters.memberInfo.avatar,
      chatList: [
        {
          question: '用js给我写个用户名验证',
        },
      ],

    };
  },

  components: {
    memberPopup,
    MarkdownItVueLight
  },
  directives: {
    'enter-prevent': {
      inserted: function (el, binding) {
        el.addEventListener('keydown', function (event) {
          if (event.keyCode === 13 && !event.shiftKey) {
            event.preventDefault();
            event.stopPropagation();
            // 执行绑定的函数
            binding.value();
          }
        });
      }
    }
  },
  methods: {
    addSearch() {
      let that = this;
      this.getPrompt().then(
          res => {
            if (res.code === 1) {
              that.cats = res.result;
              that.changeCat(that.cats.length - 1)
            }
          }
      )
    },
    search() {
      let that = this;
      this.getPrompt().then(
          res => {
            if (res.code === 1) {
              that.cats = res.result;
              that.changeCat(that.cats.length - 1)
            }
          }
      )
    },
    changeCat(index) {
      this.page = 1;
      this.catIndex = index;
      this.cats[this.catIndex].lists = [];
      this.getContentList()
    },
    getContentList(){
      let loadingInstance = Loading.service({});
      let id = this.cats[this.catIndex].id;
      let that = this;
      that.axios.post('/api/chatPrompt/getListByClass', {id, keywords: this.prompt_keywords, page: this.page}).then(
          res => {
            this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
              loadingInstance.close();
            });
            if (res.code === 1) {
              that.cats[that.catIndex].lists =  that.cats[that.catIndex].lists.concat(res.result);
            }
          }
      )
    },
    getMore(){
      this.page ++;
      this.getContentList()
    },
    timestampToDate(timestamp) {
      let date = new Date(timestamp * 1000);

      let year = date.getFullYear();
      let month = ("0" + (date.getMonth() + 1)).slice(-2); // Months are zero-based
      let day = ("0" + date.getDate()).slice(-2);

      return `${year}-${month}-${day}`;
    },
    initNewChat() {
      this.msg = '';
      this.infos = [];
      this.chatIndex = -1;
      this.showLoading = false;
      this.prompt_keywords = '';
      let that = this;
      this.getPrompt().then(
          res => {
            if (res.code === 1) {
              that.cats = res.result;
              let len = that.cats.length;
              if(that.cats[len - 2]['count'] > 0) {
                that.changeCat(len - 2)
              }else{
                that.changeCat(len - 1)
              }
            }
          }
      )
      this.getChatList()
    },
    usePrompt(item) {
      this.infos = [item]
      this.prompt_placeholder = item.title + "\n"
    },
    unlike(id) {
      let that = this;
      this.axios.post('/api/chatPromptMember/delete', {id}).then(
          res => {
            if (res.code === 1) {
              that.fav_ids = res.result.ids;
              that.cats[that.cats.length - 2]['lists'] = res.result.data
              that.cats = JSON.parse(JSON.stringify(that.cats))
              that.$message.success('删除常用成功')
            }
          }
      )
    },
    like(id) {
      let that = this;
      this.axios.post('/api/chatPromptMember/add', {id}).then(
          res => {
            if (res.code === 1) {
              that.fav_ids = res.result.ids;
              that.cats[that.cats.length - 2]['lists'] = res.result.data
              that.cats = JSON.parse(JSON.stringify(that.cats))
              that.$message.success('保存常用成功')
            }
          }
      )
    },
    addNewChat() {
      if (this.showLoading == true) {
        return;
      }
      this.showLoading = true; // 显示 loading
      let that = this;
      this.axios.post('/api/chat/getAccess', {msg: that.msg}).then(
          res => {
            if (res.code === 1) {
              let id = 0;
              if (that.infos[0]) {
                id = that.infos[0].id
              }
              let key = res.result.key;
              that.axios.post('/api/chat/add', {id, name: that.msg.substr(0, 15)}).then(
                  res => {
                    if (res.code === 1) {
                      that.chats = res.result
                      that.chatIndex = 0;
                      that.prompt_placeholder = '请输入您的问题。(Shift + Enter = 换行)';
                      that.chatList = [];
                      that.receiveMsg(key)
                    }
                  }
              )

            } else {
              this.showLoading = false;
              if (res.result && res.result.action) {
                let action = res.result.action;
                if (action === 'recharge') {
                  that.rechargeShow = true;
                }
                if (action === 'login') {
                  that.showLogin = true;
                }
              }
            }
          }
      )
    },
    receiveMsg(key) {
      let that = this;
      that.chatList.push({
        content: that.msg,
        response: '',
      })
      that.msg = '';
      let source = new EventSource(that.baseURL + `/api/common/generateChatMsg?key=${key}&event_name=newChatMsg&chat_id=` + that.chats[that.chatIndex].id);

      //监听test事件
      source.addEventListener('newChatMsg', function (event) {
        if (event.data) {
          if (event.data === 'end') {
            that.showLoading = false;
            source.close()
          } else {
            let res = event.data
            res = JSON.parse(res)

            // 如果返回错误 根据提示信息提示
            if(res.alert){
              that.$alert(res.alert, '提示', {
                confirmButtonText: '确定',
              });
              return;
            }
            //--------------------------


            res = res.title
            let len = that.chatList.length;
            that.chatList[len - 1].response += res;
            that.chatList = JSON.parse(JSON.stringify(that.chatList))

          }
        }
        const contentEl = window.scrollTo(0, document.body.scrollHeight);
        contentEl.scrollTop = contentEl.scrollHeight;
      });
    },
    addNewMsg() {
      if (this.showLoading == true) {
        return;
      }
      this.showLoading = true; // 显示 loading
      let that = this;
      this.axios.post('/api/chat/getAccess', {msg: that.msg}).then(
          res => {
            if (res.code === 1) {
              let key = res.result.key;
              that.receiveMsg(key)
            } else {
              if (res.result && res.result.action) {
                let action = res.result.action;
                if (action === 'recharge') {
                  that.rechargeShow = true;
                }
                if (action === 'login') {
                  that.showLogin = true;
                }
              }
            }
          }
      )
    },
    //删除按钮
    handleDelete(index) {
      this.prompt_placeholder = '请输入您的问题。(Shift + Enter = 换行)';
      // 用户点击确定后执行删除操作
      this.infos.splice(index, 1);
    },
    getPrompt() {
      return this.axios.post('/api/chatPrompt/list',{keywords: this.prompt_keywords});
    },
    copyText(question) {
      const text = removeTags(question);
      navigator.clipboard.writeText(text).then(() => {
        this.$message({
          message: '已复制',
          type: 'success'
        });
      }, () => {
        console.log('Unable to write to clipboard');
      });
    },
    //删除信息
    deleteChatList(index) {
      MessageBox.confirm(`确定删除此条信息吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        // 用户点击确定后执行删除操作
        this.chatList.splice(index, 1);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
        // 用户点击取消或者弹窗关闭时不做任何操作
      });
    },

    getChatList() {
      let that = this;
      this.axios.post('/api/chat/list').then(
          res => {
            if (res.code === 1) {
              that.chats = res.result
            }
          }
      )
    },


    //--------nav
    deleteChat(id) {
      let that = this;
      MessageBox.confirm(`确定删除此条信息吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.axios.post('/api/chat/delete', {id}).then(
            res => {
              if (res.code === 1) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                that.getChatList()
                that.initNewChat()
              }
            }
        )

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
        // 用户点击取消或者弹窗关闭时不做任何操作
      });
    },
    editChat(item, index) {
      // 遍历 items 数组，将所有元素的 inputShow 属性都设为 false，除了当前元素
      this.chats.forEach((item, i) => {
        if (i !== index) {
          item.inputShow = false;
        }
      });
      // 将当前元素的 active 属性设为 true
      item.inputShow = true;

      this.chats = JSON.parse(JSON.stringify(this.chats))
    },
    editSave(item, index) {
      // 遍历 items 数组，将所有元素的 inputShow 属性都设为 false，除了当前元素
      this.chats.forEach((item, i) => {
        if (i !== index) {
          item.inputShow = false;
        }
      });
      // 将当前元素的 active 属性设为 true
      item.inputShow = false;

      let that = this;
      this.axios.post('/api/chat/update', {id: item.id, name: item.name}).then(
          res => {
            if (res.code === 1) {
              that.$message.success('修改成功')
              that.getChatList()
            }
          }
      )
    },
    clearName(item, index) {
      // 遍历 items 数组，将所有元素的 active 属性都设为 false，除了当前元素
      item.name = ''
    },
    toggleListItemActive(item, index) {
      // 遍历 items 数组，将所有元素的 active 属性都设为 false，除了当前元素
      this.chatIndex = index
      this.getChatMsgList()
    },
    getChatMsgList() {
      let that = this;
      this.axios.post('/api/chat/getData', {id: this.chats[this.chatIndex].id}).then(
          res => {
            if (res.code === 1) {
              that.chatList = res.result;
            }
          }
      )
    }
  },
  mounted() {
    let that = this;
    this.getPrompt().then(
        res => {
          if (res.code === 1) {
            that.cats = res.result;
            let len = that.cats.length;
            if(that.cats[len - 2]['count'] > 0) {
              that.changeCat(len - 2)
            }else{
              that.changeCat(len - 1)
            }
          }
        }
    )
    this.getChatList()

  }
}
</script>

<style>
@import "home.css";
</style>
